package com.tinem.platform.module.starter.jms.util.impl;

import com.tinem.platform.module.starter.jms.enums.TopicEnum;
import com.tinem.platform.module.starter.jms.util.JmsUtil;
import lombok.extern.slf4j.Slf4j;

import javax.jms.*;

/**
 * @author fengzhihao
 * @version v1
 * @program: platform
 * @className JmsQueuesUtil
 * @description TODO
 * @site
 * @company
 * @create 2021/12/1 17:43:45
 */
@Slf4j
public class JmsTopicUtil extends JmsUtil {
    /**
     * 发送消息
     * @param t topic
     * @param body
     * @return
     */
    @Override
    public void sendMessage(String body,String applicationName,TopicEnum t,String... args){
        String topic = t.getTopic(active,applicationName,args);
        log.info("send mq message:({}):({}):",topic,body);

        //获取连接工厂
        ConnectionFactory connectionFactory = this.jmsMessagingTemplate.getConnectionFactory();
        try {
            //获取连接
            Connection connection = connectionFactory.createConnection();
            connection.start();
            //获取session
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Destination destination = getDestination(session,topic);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            TextMessage message = session.createTextMessage(body);
            //发送
            producer.send(message);
            session.commit();
            producer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected Destination getDestination(Session session,String topic) throws JMSException {
        return session.createTopic(topic);
    }
}
